package cn.edu.njtc.config;

import cn.edu.njtc.interceptor.AuthInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Autowired
    AuthInterceptor authInterceptor;


    /**
     * 添加设置拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        List<String> exclude= new ArrayList<>();
        exclude.add("/user/login");
        exclude.add("/user/register");
        exclude.add("/swagger-ui/**");

        registry.addInterceptor(authInterceptor).addPathPatterns("/**") // 拦截所有请求
                .excludePathPatterns(exclude);  // 放行个别请求
    }


    /**
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {

        //  /表示当前服务器的根地址
        registry.addMapping("/**")
                .allowedOrigins("*")  // 设置源
                .allowCredentials(false) // 允许携带cookie
                .allowedHeaders("*") // 设置请求头 TOKEN AUTHORTICATION
                .allowedMethods("*") // 允许的请求方式 POST GET
                .maxAge(3600); // 设置请求的生命周期 1小时

    }
}
